package com.imooc.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imooc.pojo.GoodsInfo;
import com.imooc.service.GoodsInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("goodsinfo")
public class GoodsInfoController {

    @Autowired
    private GoodsInfoService goodsInfoService;

    private int currentPage = 0, pageSize= 30;

    @RequestMapping(value = {"/query/{pageNum}"})
    public String query(HttpServletRequest request, Model model, @PathVariable("pageNum") int pageNum) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String goodsId = request.getParameter("goodsId");
        if (StringUtils.isNotEmpty(goodsId)){
            jsonObject.put("goodsId", goodsId);
        }
        String goodsTypeId = request.getParameter("goodsTypeId");
        if (StringUtils.isNotEmpty(goodsTypeId)){
            jsonObject.put("goodsTypeId", goodsTypeId);
        }
        currentPage = pageNum;
        PageInfo deviceUserecordCustomList = goodsInfoService.getAllGoodsInfo(jsonObject, currentPage, pageSize);
        model.addAttribute("deviceUserecordCustomList", deviceUserecordCustomList);

        return "thymeleaf/see_log";
    }

    /**
     * 清空表数据
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/del/all"})
    public String delAllData(Model model) throws Exception {
        goodsInfoService.truncateGoodsInfo();
        return "thymeleaf/see_log";
    }

    //查询单个item
    @RequestMapping(value = {"/get/{id}"})
    public String get(Model model, @PathVariable("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        GoodsInfo goodsInfo = goodsInfoService.getGoodsInfo(map);

        model.addAttribute("goodsInfo", goodsInfo);
        return "thymeleaf/update_goodsinfo";
    }

    @RequestMapping(value = {"/update"})
    public void updateGoodsInfo(Model model, GoodsInfo goodsInfo, HttpServletResponse response) throws Exception {
        goodsInfoService.updateByParam(goodsInfo);
        response.sendRedirect("query");
    }

    @RequestMapping(value = {"/del/{id}"})
    public String delGoodsInfo(Model model, @PathVariable("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        goodsInfoService.deleteByParam(map);
        return "thymeleaf/see_log";
    }
}
